const friendModel = require('../models/friendModel');
const {getHexByLength} = require("../utils/generateHex");

const getFriends = (req, res) => {
    const userId = req.params.userId

    friendModel.getFriendsByUid(userId).then(rs => {
        return res.status(200).send(rs).end()
    }).catch(err => {
        return res.status(500).send(err).end()
    })
}

const getFriendsId = (req, res) => {
    const uid = req.query.uid

    friendModel.getFriendsIdByUid(uid).then(rs => {
        return res.status(200).send(rs).end()
    }).catch(err => {
        return res.status(500).send(err).end()
    })
}

const sendFriendRequest = (req, res) => {
    const { sender_id, receiver_id } = req.body
    friendModel.createNewFriendRequest(sender_id, receiver_id).then(rs => {
        return res.status(200).end()
    }).catch(err => {
        return res.status(500).send(err)
    })
}

const getFriendRequest = (req, res) => {
    const uid = req.query.uid
    friendModel.getFriendRequestById(uid).then(rs => {
        return res.status(200).send(rs).end()
    }).catch(err => {
        return res.status(500).send(err).end()
    })
}

const checkRelationship = (req, res) => {
    const {uid_1, uid_2} = req.query
    friendModel.checkRelationshipByUid(uid_1, uid_2).then(rs => {
        return res.status(200).send(rs).end()
    }).catch(err => {
        return res.status(500).send(err).end()
    })
}

const acceptFriendRequest = (req, res) => {
    const {receiver_id, sender_id } = req.body
    friendModel.setFriendshipByUid(receiver_id, sender_id, getHexByLength(9)).then(rs => {
        return res.status(200).send(rs).end()
    }).catch(err => {
        return res.status(500).send(err).end()
    })
}

const ignoreFriendRequest = (req, res) => {
    const {receiver_id, sender_id} = req.body
    friendModel.ignoreFriendRequestByUid(receiver_id, sender_id).then(rs => {
        return res.status(200).send(rs).end()
    }).catch(err => {
        return res.status(500).send(err).end()
    })
}

const checkFriendReqStatus = (req, res) => {
    const {sender_id, receiver_id} = req.query
    friendModel.checkFriendReqStatusByUid(sender_id, receiver_id).then(rs => {
        return res.status(200).send(rs).end()
    }).catch(err => {
        return res.status(500).send(err).end()
    })
}

const checkIfHasFriendRequest = (req, res) => {
    const {sender_id, receiver_id} = req.query
    friendModel.getFriendRequest(sender_id, receiver_id)
        .then(rs => res.status(200).send(rs))
        .catch(err => res.status(500).send(err))
}


module.exports = {
    getFriends,
    getFriendsId,
    sendFriendRequest,
    getFriendRequest,
    checkRelationship,
    acceptFriendRequest,
    ignoreFriendRequest,
    checkFriendReqStatus,
    checkIfHasFriendRequest
};